package handler

import (
	"github.com/gin-gonic/gin"
	"user-auth-sys/model"
	"user-auth-sys/pkg"
)

func Register(c *gin.Context) {
	username := c.PostForm("username")
	password := pkg.Md5(c.PostForm("password"))
	if username == "" || password == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "字段不可为空",
		})
		return
	}
	user := model.User{
		Username: username,
		Password: password,
	}
	model.DB.Where("username = ?", username).Find(&user)
	if user.ID > 0 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "用户名已被注册",
		})
		return
	}
	model.DB.Create(&user)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "注册成功",
		"user": user,
	})
	return
}
func Login(c *gin.Context) {
	username := c.PostForm("username")
	password := c.PostForm("password")
	if username == "" || password == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "字段不可为空",
		})
		return
	}
	var user model.User
	model.DB.Where("username = ?", username).Find(&user)
	if user.ID == 0 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "用户不存在",
		})
		return
	}
	if user.Password != pkg.Md5(password) {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "密码错误",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "登录成功",
		"user": user,
	})
	return
}
